const Koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const jwt = require('jsonwebtoken')
const jwtKoa = require('koa-jwt')

var admin = require('./routes/user/admin.js')
var newList = require('./routes/news/list.js')
var login = require('./routes/user/login.js')
const DB = require('./utils/db.js')
const keys = require('./utils/config')

const app = new Koa()
const router = new Router()

const secret = 'secret'

app.use(jwtKoa({ secret }).unless({
  path: [/\/register/, /\/login/]
}))

app.use(bodyParser())

app.use(async (ctx, next) => {
  console.log(ctx)
  let params = Object.assign({}, ctx.request.query, ctx.request.body);
  ctx.request.header = { 'authorization': "Bearer " + (params.token || '') }
  await next();
})

router.get('/', async (ctx) => {
  ctx.body = 'home'
})

router.post('/register', async (ctx) => {
  let email = ctx.request.body.email

  const findResult = await DB.find('author', {
    'email': email
  })

  if (findResult.length > 0) {
    ctx.status = 506
    ctx.body = { email: '邮箱已被占用 ' }
  } else {
    let data = await DB.insert('author', ctx.request.body)
    ctx.body = data
    try {
      if (data.result.ok) {
        ctx.body = {
          mssage: '注册成功'
        }
      }
    } catch (error) {
      console.log(error)
      // ctx.redirect('/')
    }
  }
})

router.post('/login', async (ctx, next) => {
  let name = ctx.request.body.name
  let email = ctx.request.body.email
  let pwd = ctx.request.body.pwd

  var result = await DB.find('author',
    { 'name': name, 'email': email })

  if (result.length === 0) {
    ctx.status = 404
    ctx.body = { email: '用户不存在!' }
  } else {
    var result = await DB.find('author', { 'pwd': pwd })
    if (result) {
      // 返回token
      const payload = { pwd: pwd, name: name }
      const token = jwt.sign(payload, keys.secretOrkey, { expiresIn: 3600 })

      ctx.status = 200
      ctx.body = { success: true, token: 'Bearer ' + token }
    } else {
      ctx.status = 400
      ctx.body = { password: '密码错误!' }
    }
  }
})

router.use('/admin', admin.routes())
router.use('/news', newList.routes())
router.use('/login', login.routes())

app.use(router.routes()).use(router.allowedMethods())

app.listen(3000)